package servlet;

import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        //获取两个验证码比较
        String checkcode_session = (String) request.getSession( ).getAttribute("checkcode_session");
        request.getSession().removeAttribute("checkcode_session");
        String code = request.getParameter("verifycode");
        System.out.println(checkcode_session );
        System.out.println(code );
        //你是煞笔码  这里验证码不忽略大小写比较 你永远错都是验证码错误
        if (code==null||!checkcode_session.equalsIgnoreCase(code)){
            //提示错误信息
            request.setAttribute("error","验证码错了,轩");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }

        //接下来就是获取提交的参数了
        Map<String, String[]> map = request.getParameterMap( );
        User loginUser = new User();
        try {
            BeanUtils.populate(loginUser,map);
            System.out.println("lo"+loginUser );
        } catch (IllegalAccessException e) {
            e.printStackTrace( );
        } catch (InvocationTargetException e) {
            e.printStackTrace( );
        }
        //带着User 去数据库查
        UserService service = new UserServiceImpl();
        User user = service.findThisUser(loginUser);
        System.out.println(user );
        if (user==null){
            request.setAttribute("error","账户密码错了,轩");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else {
            //登陆成  我地址栏要变化  所以重定向
            request.getSession().setAttribute("user",user);
            response.sendRedirect("/day20/index.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
